#include "listcalc.h"

ListCalc::ListCalc(QObject *parent, bool critical) :
    QThread(parent), _critical(critical)
{
}

void ListCalc::run()
{
    QString fileName("update.lst");
    QFile fichier(fileName);
    fichier.open(QIODevice::ReadOnly);
    QTextStream flux(&fichier);
    QString ligne;
    while(!flux.atEnd())
    {
        ligne = flux.readLine();
        if (ligne == "[misc]")
        {
            ligne = flux.readLine();
            QString addr_server = ligne.section('=', 1, 1);
        }
        else if (ligne == "[files]")
        {
            ligne = flux.readLine();
            int file_count = ligne.section('=', 1, 1).toInt();
            int i = 0;
            while (i < file_count)
            {
                ligne = flux.readLine();
                if (_critical == false || ligne.section('|', 2, 2) == "c")
                {
                    emit checkFile(QString("Checking :").append(ligne.section('|', 0, 0).section('=', 1, 1)));
                    if (CalcSha1(ligne.section('|', 0, 0).section('=', 1, 1)) != ligne.section('|', 1, 1)){
                        file_list.append(ligne.section('=', 1, 1).section('|', 0, 0));
                    }
                }
                i++;
            }
        }
    }
    fichier.close();
    QStringListModel *modele = new QStringListModel(file_list);
    emit giveModel(modele);
    emit giveTPbar(file_list.size());
    emit giveTPbarVal(0);
}

QString ListCalc::CalcSha1(QString Path)
{
        QFile FileToHash(Path);
        QByteArray ba;
        QString HashOutput;
        QCryptographicHash CPU(QCryptographicHash::Sha1);
        if (FileToHash.open(QIODevice::ReadOnly))
        {
                while (!FileToHash.atEnd())
                {
                        ba = FileToHash.read(1024);
                        CPU.addData(ba);
                }
                FileToHash.close();
                ba = CPU.result();
                HashOutput = ba.toHex();
                return HashOutput;
        }
        else
        {
                HashOutput = "ERR";
                return HashOutput;
        }
}
